﻿using log4net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Telerik.Windows.Controls;
using TruckScale.Models;

namespace TruckScale.Views
{
  /// <summary>
  /// Interaction logic for DMCarDetailView.xaml
  /// </summary>
  public partial class DMCarDetailView : RadWindow, INotifyPropertyChanged
  {
    //log
    private static readonly log4net.ILog log = LogManager.GetLogger("DMCarDetailView");
    //新增后同步刷新列表
    public event PropertyChangedEventHandler PropertyChanged;

    public string InfoBar { get; set; }
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public CarModel Car { get; set; }
    public List<CustomerModel> CustomerList { get; set; } = CustomerModel.SelectCustomerByType("运输");
    public CustomerModel SelectedCustomer { get; set; }
    private CarModel OldCar;
    public DMCarDetailView(CarModel car)
    {
      InitializeComponent();
      this.DataContext = this;

      if (car != null)
      {
        Car = car;
        SelectedCustomer = CustomerList.Find(c => c.CustomerId == Car.CarOwner);
        OldCar = new CarModel()
        {
          PlateNo = car.PlateNo
        };
      }
      else
      {
        Car = new CarModel();
      }
    }
    private void RadButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
      InfoBar = string.Empty;
      Car.CarOwner = SelectedCustomer?.CustomerId;

      if (Car.VehicleWeight == "")
      {
        Car.VehicleWeight = null;
      }

      if (Car.VehicleWeight != null && !Regex.IsMatch(Car.VehicleWeight, @"^\d+(\.\d+)?$"))
      {
        InfoBar = "保存失败，车辆皮重格式不正确！";
        return;
      }

      if (Car.CarId == null)
      {
        if (0 < CarModel.InsertCar(Car))
        {
          this.Close();
        }
        else
        {
          InfoBar = "保存失败，请检查信息是否完整或已存在！";
        }
      }
      else
      {
        if (0 < CarModel.UpdateCar(Car))
        {
          CarModel.UpdateUsedCar(Car.PlateNo, OldCar.PlateNo);
          this.Close();
        }
        else
        {
          InfoBar = "保存失败，请检查信息是否完整或已存在！";
        }
      }

    }
  }
}
